package com.weibo.api;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.weibo.WBAction;
import com.weibo.bean.WBMsg;
import com.weibo.bean.WBMsgData;
import com.weibo.bean.WBReMsg;
import com.weibo.service.WeiBoReplyService;

/**
 * 消息回复接口
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date 2014-4-15 上午10:41:34
 */
public class WBReply {

	private static final Logger logger = Logger.getLogger(WBReply.class);

	private static final String DEFAULT_HANDLER = "com.weibo.service.WeiBoReplyServiceImpl";
	private static Class<?> messageHandlerClazz = null;

	public WBReply() {}

	/**
	 * 回调消息
	 * @param action
	 * @param msg
	 * @return
	 */
	private static String call(WBAction action, WBMsg<WBMsgData> msg){
		logger.info("消息解析前..." + msg.toString());
		WBReMsg reMsg = action._do(msg);
		if (null == reMsg) {
			return ""; // 假如开发者无法保证在五秒内处理并回复，可以直接回复空串，微博服务器不会对此作任何处理，并且不会发起重试
		}
		reMsg.setSenderId(msg.getReceiverId());
		reMsg.setReceiverId(msg.getSenderId());
		reMsg.setResult(true);
		logger.info("消息解析后..." + reMsg.toString());
		return JSONObject.toJSONString(reMsg);
	}
	
	/**
	 * 处理消息
	 * @param msg
	 * @return
	 */
	public static String parseMsg(WBMsg<WBMsgData> msg) {
		return call(new WBAction() {
			@Override
			public WBReMsg _do(WBMsg<WBMsgData> msg) {
				// 加载处理器
				if (messageHandlerClazz == null) {
					// 获取自定消息处理器，如果自定义处理器则使用默认处理器。
					String handler = WeiBo.props.get("message_handler");
					handler = handler == null ? DEFAULT_HANDLER : handler;
					try {
						messageHandlerClazz = Thread.currentThread().getContextClassLoader().loadClass(handler);
					} catch (Exception e) {
						throw new RuntimeException("messageHandlerClazz Load Error！");
					}
				}
				try {
					WeiBoReplyService WeiBoReplyService = (WeiBoReplyService) messageHandlerClazz.newInstance();
					//取得消息类型
					String type = msg.getType();
					Method method = WeiBoReplyService.getClass().getMethod(type + "TypeMsg", WBMsg.class);
					WBReMsg reMsg = (WBReMsg) method.invoke(WeiBoReplyService, msg);
					// 统一处理Data
					String jsonText = reMsg.getData();
					if (StringUtils.isNotBlank(jsonText)) {
						reMsg.setData(URLEncoder.encode(jsonText, "UTF-8"));
						return reMsg;
					}
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				return null;
			}
		}, msg);
	}
}
